const redis = require('redis')
const noop = () => undefined;

module.exports = function (session) {

    class RedisStore extends session.Store {
        constructor(options) {
            super(options)
            this.client = redis.createClient(options.client)
            this.prefix = options.prefix

            this.client.on('error', function (err) {
                console.log("command:" + err.command);
                console.log("args:", err.args);
                console.log("code:" + err.code);
            });

            this.client.on('connect', function () {
                console.log('sessionStore connected')
            });
        }

        get(sid, fn) {
            let store = this
            let psid = store.prefix + sid;
            if (!fn) fn = noop

            store.client.get(psid, function (er, data) {
                if (er) return fn(er)
                if (!data) return fn()

                try {
                    data = JSON.parse(data);
                } catch (er) {
                    return fn(er);
                }
                return fn(null, data);
            });
        }


        set(sid, sess, fn) {
            let store = this
            let sessionStr = store.prefix + sid
            let ttl = sess.cookie.maxAge
            let jsess = null

            if (!fn) fn = noop;

            try {
                jsess = JSON.stringify(sess);
            } catch (er) {
                return fn(er);
            }

            store.client.set([sessionStr, jsess, 'EX', ttl], function (er) {
                if (er) return fn(er);
                fn.apply(null, arguments);
            });
        }

        destroy(sid, fn) {
            sid = this.prefix + sid;
            this.client.del(sid, fn);
        }
    }
    return RedisStore
}